package org.jeecg.modules.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysSms;
import org.jeecg.modules.system.service.ISysSmsService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 短信
 * @Author: jeecg-boot
 * @Date:   2021-02-04
 * @Version: V1.0
 */
@Slf4j
@Api(tags="短信")
@RestController
@RequestMapping("b/system/sysSms")
public class SysSmsController {
	@Autowired
	private ISysSmsService sysSmsService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
    private final String smsRules = "短信字数含\"签名+模版内容+变量内容”，短信70个字数含以内，按1条短信计费；超出70个字为长短信，按照67个字数记为1条短信费用。";
    /**
	 * 分页列表查询
	 * @param sysSms
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "短信-分页列表查询")
	@ApiOperation(value="短信-分页列表查询", notes="短信-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<SysSms>> queryPageList(SysSms sysSms,
											   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
											   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
											   HttpServletRequest req) {
		Result<IPage<SysSms>> result = new Result<IPage<SysSms>>();
		sysSms.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(), "p", sysSms.getMenuPath(), null, sysSms.getDepartIdEx()));
		QueryWrapper<SysSms> queryWrapper = QueryGenerator.initQueryWrapper(sysSms, req.getParameterMap());
		Page<SysSms> page = new Page<SysSms>(pageNo, pageSize);
		IPage<SysSms> pageList = sysSmsService.findPage(page, sysSms);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<SysSms> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              SysSms sysSms = JSON.parseObject(deString, SysSms.class);
              queryWrapper = QueryGenerator.initQueryWrapper(sysSms, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<SysSms> pageList = sysSmsService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "短信列表");
      mv.addObject(NormalExcelConstants.CLASS, SysSms.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("短信列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }


   public boolean addMessage(SysSms sms){
	   Result<Object> result = new Result<>();
	   if (sms.getEsContent() == null){
	   	return false;
	   }
	   if (StringUtils.isEmpty(sms.getProjectId())){
	   	return false;
	   }
	   if (sms.getEsType() == null){
	   	return false;
	   }
	   if (StringUtils.isEmpty(sms.getBusinessId())){
	   	return false;
	   }
       if (sms.getTenantId() == null){
       	return false;
	   }
       sms.setTenantId(sms.getTenantId());
       //查询渠道对应的短信金额
	  String tAmount =  sysSmsService.queryTenantMount(sms.getTenantId());
       if (StringUtils.isEmpty(tAmount)){
       	return false;
	   }
	   BigDecimal tenantAmount = new BigDecimal(tAmount);
       BigDecimal smsAmount = BigDecimal.ZERO;
	   int length = sms.getEsContent().toString().length();
	   BigDecimal bLength = new BigDecimal(length);
	   BigDecimal standLength = new BigDecimal(67);
	   if (length >70){
		   smsAmount =  (bLength.subtract(standLength)).divide(standLength).add(new BigDecimal(1)).multiply(tenantAmount) ;
	   }else {
	   	smsAmount = tenantAmount;
	   }
	   sms.setAmount(smsAmount.toString());
	   sms.setSmsRules(smsRules);
	   try {
	   	sysSmsService.save(sms);

	   }catch (Exception e){
	   	log.info(e.getMessage());
	   }
	   return true;
   }


}
